package com.github.sbb.sherry.primitives.core;


import com.github.sbb.sherry.common.collect.CollectionUtil;
import com.github.sbb.sherry.primitives.api.Converter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * ConverterPool 用来存储当前的所有的 converter
 *
 * @author zhangyunan
 */
public class ConverterPool {

    private static Map<String, Converter> converterMap = new ConcurrentHashMap<>();

    private static List<ConverterFetchSupplier> converterFetchSupplierList;

    public static synchronized void addFetchSupplier(ConverterFetchSupplier converterFetchSupplier) {
        if (converterFetchSupplierList == null) {
            converterFetchSupplierList = new ArrayList<>();
        }
        converterFetchSupplierList.add(converterFetchSupplier);
    }

    public static void addConverter(Converter converter) {
        converterMap.put(converter.name(), converter);
    }

  public static void addConverter(Class<? extends Converter> converterClass) {
    try {
      Converter converter = converterClass.newInstance();
      addConverter(converter);
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }

  public static Converter getConverter(String name) {
    Converter converter = converterMap.get(name);
    if (converter == null && CollectionUtil.isNotEmpty(converterFetchSupplierList)) {
      for (ConverterFetchSupplier converterFetchSupplier : converterFetchSupplierList) {
        converter = converterFetchSupplier.get(name);
        if (converter != null) {
          addConverter(converter);
          return converter;
        }
      }
    }
    return converter;
    }
}
